package smarthouse.ejb;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import smarthouse.conv.Conversions;
import smarthouse.dto.RoomDTO;
import smarthouse.model.Room;

/**
 * Session Bean implementation class RoomDTO
 */
@Stateless
@Local
public class RoomDAO implements RoomDAORemote {

	@EJB
	Conversions conv;

	@PersistenceContext
	EntityManager em;

	/**
	 * Default constructor.
	 */
	public RoomDAO() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public RoomDTO getRoombyId(int id) {
		TypedQuery<Room> usersReturn = em.createNamedQuery("Room.findAll",
				Room.class);

		List<Room> users = usersReturn.getResultList();
		for (Room u : users) {
			if (u.getRoomId() == id) {
				return conv.room_C_2_DTO(u);
			}
		}

		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean addRoom(RoomDTO user) {
		Room u = em.find(Room.class, user.getRoomId());

		if (u == null) {
			em.persist(conv.room_DTO_2_C(user));
			return true;
		} else {
			em.merge(conv.room_DTO_2_C(user));
			return true;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean updateRoom(RoomDTO user) {
		Room u = em.find(Room.class, user.getRoomId());
		if (u == null) {
			return false;
		} else {
			u.setLight(user.getLight());
			u.setSize(user.getSize());
			u.setTemperature(user.getTemperature());
			u.setType(user.getType());
			em.merge(u);
			return true;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean removeRoom(int id) {
		Room u = em.find(Room.class, id);

		if (u == null) {
			return false;
		} else {
			em.remove(u);
			return true;
		}

	}

}
